package com.google.code.drift.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.google.code.drift.R;
import com.google.code.drift.adapter.ChatRoomContentAdapter;
import com.google.code.drift.api.AppSkyApp;
import com.google.code.drift.api.ChatMessage;
import com.google.code.drift.api.Refreshable;
import com.google.code.drift.utils.AlertUtils;
import com.google.code.drift.utils.CommonUtils;

public class TraditionChatActivity extends Activity implements Refreshable {

	private ListView mainList;

	private AppSkyApp app;

	private boolean isRegistReceiver = false;

	private AlertUtils alert;

	private ArrayList<ChatMessage> chatMessageList = new ArrayList<ChatMessage>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chat_tradition_mod_layout);
		app = (AppSkyApp) getApplication();
		alert = new AlertUtils(this);

		initView();
	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter(
				CommonUtils.ACTION_CHAT_MESSAGE_RECEIVER);
		isRegistReceiver = true;
		registerReceiver(chatMessageReceiver, filter);
		super.onStart();
	}

	@Override
	public void refresh() {
		
	}
	
	@Override
	protected void onDestroy() {
		if (chatMessageList != null) {
			chatMessageList.clear();
			chatMessageList = null;
		}
		if (isRegistReceiver) {
			unregisterReceiver(chatMessageReceiver);
			isRegistReceiver = false;
			chatMessageReceiver = null;
		}
		if (alert != null) {
			alert.release();
			alert = null;
		}
		super.onDestroy();
	}

	private void initView() {
		mainList = (ListView) findViewById(R.id.main_list);
		ChatRoomContentAdapter adapter = new ChatRoomContentAdapter(this,
				chatMessageList);
		mainList.setAdapter(adapter);
	}

	private BroadcastReceiver chatMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			JSONObject json = JSONObject.parseObject(intent
					.getStringExtra("json"));
			int id = json.getIntValue("id");
			boolean isMe;
			if (id == app.getMyInfo().getUserId()) {
				isMe = true;
			} else {
				isMe = false;
			}
			ChatMessage chatMessage = new ChatMessage(json, isMe);
			chatMessageList.add(chatMessage);
			mainList.setSelection(chatMessageList.size() - 1);
			if (!isMe) {
				// TODO 铃声或震动
				alert.alert();
			}
		}
	};

}
